<!DOCTYPE html>
<html lang="en-us" dir="ltr">
    <head><meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'><meta name='description' content='celery 执行work /usr/local/python3.7/bin/python3.7 -m celery -A pucha worker -l info -n w1@localhost.localdomain &amp;ndash;pidfile=/var/run/celery/w1.pid &amp;ndash;logfile=/var/log/celery.log
执行beat celery -A pucha beat -l info -f /var/log/celery/celery.log &amp;ndash;detach
redis-cli使用 string：字符串构建其他数据结构的基础
hash：哈希列表
list（可重复）：列表
set（不可重复无序）：集合，在哈希列表的基础上实现
sorted set（不可重复有序）：有序集合
使用场景
去最新n个数据的操作 排行榜，取top n个数据 //最佳人气前10条 精确的设置过期时间 计数器 实时系统， 反垃圾系统 pub， sub发布订阅构建实时消息系统 构建消息队列 缓存 cmd访问redis redis-cli.exe -h 127.0.0.1 -p 6379
key keys * 获取所有的key select 0 选择第一个库 move myString 1 将当前的数据库key移动到某个数据库,目标库有，则不能移动 flush db 清除指定库 randomkey 随机key type key 类型
set key1 value1 设置keyget key1 获取keymset key1 value1 key2 value2 key3 value3（mass大量，堆）mget key1 key2 key3del key1 删除keyexists key 判断是否存在keyexpire key 10 10过期(单位是秒）pexpire key 1000 毫秒（单位是毫秒）persist key 删除过期时间string set name cxx get name getrange name 0 -1 字符串分段 getset name new_cxx 设置值，返回旧值 mset key1 key2 批量设置 mget key1 key2 批量获取 setnx key value 不存在就插入（not exists） setex key time value 过期时间（expire） setrange key index value 从index开始替换value incr age 递增 incrby age 10 递增 decr age 递减 decrby age 10 递减 incrbyfloat 增减浮点数 append 追加 strlen 长度 getbit/setbit/bitcount/bitop 位操作'><title>redis和celery笔记</title>

<link rel='canonical' href='http://meruro.cn/p/redis%E5%92%8Ccelery%E7%AC%94%E8%AE%B0/'>

<link rel="stylesheet" href="/scss/style.min.5a8e892f6fa14515e9065eee1f5d2e05302606ec7f11750b2fb95198f9cdcbfd.css"><meta property='og:title' content='redis和celery笔记'>
<meta property='og:description' content='celery 执行work /usr/local/python3.7/bin/python3.7 -m celery -A pucha worker -l info -n w1@localhost.localdomain &amp;ndash;pidfile=/var/run/celery/w1.pid &amp;ndash;logfile=/var/log/celery.log
执行beat celery -A pucha beat -l info -f /var/log/celery/celery.log &amp;ndash;detach
redis-cli使用 string：字符串构建其他数据结构的基础
hash：哈希列表
list（可重复）：列表
set（不可重复无序）：集合，在哈希列表的基础上实现
sorted set（不可重复有序）：有序集合
使用场景
去最新n个数据的操作 排行榜，取top n个数据 //最佳人气前10条 精确的设置过期时间 计数器 实时系统， 反垃圾系统 pub， sub发布订阅构建实时消息系统 构建消息队列 缓存 cmd访问redis redis-cli.exe -h 127.0.0.1 -p 6379
key keys * 获取所有的key select 0 选择第一个库 move myString 1 将当前的数据库key移动到某个数据库,目标库有，则不能移动 flush db 清除指定库 randomkey 随机key type key 类型
set key1 value1 设置keyget key1 获取keymset key1 value1 key2 value2 key3 value3（mass大量，堆）mget key1 key2 key3del key1 删除keyexists key 判断是否存在keyexpire key 10 10过期(单位是秒）pexpire key 1000 毫秒（单位是毫秒）persist key 删除过期时间string set name cxx get name getrange name 0 -1 字符串分段 getset name new_cxx 设置值，返回旧值 mset key1 key2 批量设置 mget key1 key2 批量获取 setnx key value 不存在就插入（not exists） setex key time value 过期时间（expire） setrange key index value 从index开始替换value incr age 递增 incrby age 10 递增 decr age 递减 decrby age 10 递减 incrbyfloat 增减浮点数 append 追加 strlen 长度 getbit/setbit/bitcount/bitop 位操作'>
<meta property='og:url' content='http://meruro.cn/p/redis%E5%92%8Ccelery%E7%AC%94%E8%AE%B0/'>
<meta property='og:site_name' content='梅鲁梅鲁梅鲁梅~'>
<meta property='og:type' content='article'><meta property='article:section' content='Post' /><meta property='article:tag' content='代码' /><meta property='article:published_time' content='2018-06-18T22:00:07&#43;00:00'/><meta property='article:modified_time' content='2018-06-18T22:00:07&#43;00:00'/>
<meta name="twitter:title" content="redis和celery笔记">
<meta name="twitter:description" content="celery 执行work /usr/local/python3.7/bin/python3.7 -m celery -A pucha worker -l info -n w1@localhost.localdomain &amp;ndash;pidfile=/var/run/celery/w1.pid &amp;ndash;logfile=/var/log/celery.log
执行beat celery -A pucha beat -l info -f /var/log/celery/celery.log &amp;ndash;detach
redis-cli使用 string：字符串构建其他数据结构的基础
hash：哈希列表
list（可重复）：列表
set（不可重复无序）：集合，在哈希列表的基础上实现
sorted set（不可重复有序）：有序集合
使用场景
去最新n个数据的操作 排行榜，取top n个数据 //最佳人气前10条 精确的设置过期时间 计数器 实时系统， 反垃圾系统 pub， sub发布订阅构建实时消息系统 构建消息队列 缓存 cmd访问redis redis-cli.exe -h 127.0.0.1 -p 6379
key keys * 获取所有的key select 0 选择第一个库 move myString 1 将当前的数据库key移动到某个数据库,目标库有，则不能移动 flush db 清除指定库 randomkey 随机key type key 类型
set key1 value1 设置keyget key1 获取keymset key1 value1 key2 value2 key3 value3（mass大量，堆）mget key1 key2 key3del key1 删除keyexists key 判断是否存在keyexpire key 10 10过期(单位是秒）pexpire key 1000 毫秒（单位是毫秒）persist key 删除过期时间string set name cxx get name getrange name 0 -1 字符串分段 getset name new_cxx 设置值，返回旧值 mset key1 key2 批量设置 mget key1 key2 批量获取 setnx key value 不存在就插入（not exists） setex key time value 过期时间（expire） setrange key index value 从index开始替换value incr age 递增 incrby age 10 递增 decr age 递减 decrby age 10 递减 incrbyfloat 增减浮点数 append 追加 strlen 长度 getbit/setbit/bitcount/bitop 位操作">
    </head>
    <body class="
    article-page
    ">
    <script>
        (function() {
            const colorSchemeKey = 'StackColorScheme';
            if(!localStorage.getItem(colorSchemeKey)){
                localStorage.setItem(colorSchemeKey, "auto");
            }
        })();
    </script><script>
    (function() {
        const colorSchemeKey = 'StackColorScheme';
        const colorSchemeItem = localStorage.getItem(colorSchemeKey);
        const supportDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches === true;

        if (colorSchemeItem == 'dark' || colorSchemeItem === 'auto' && supportDarkMode) {
            

            document.documentElement.dataset.scheme = 'dark';
        } else {
            document.documentElement.dataset.scheme = 'light';
        }
    })();
</script>
<div class="container main-container flex on-phone--column extended"><aside class="sidebar left-sidebar sticky ">
    <button class="hamburger hamburger--spin" type="button" id="toggle-menu" aria-label="Toggle Menu">
        <span class="hamburger-box">
            <span class="hamburger-inner"></span>
        </span>
    </button>

    <header>
        
            
            <figure class="site-avatar">
                <a href="/">
                
                    
                    
                    
                        
                        <img src="/img/ava_hu31add2dceb44736f969f74989490346b_19511_300x0_resize_q75_box.jpg" width="300"
                            height="300" class="site-logo" loading="lazy" alt="Avatar">
                    
                
                </a>
                
                    <span class="emoji">🍥</span>
                
            </figure>
            
        
        
        <div class="site-meta">
            <h1 class="site-name"><a href="/">梅鲁梅鲁梅鲁梅~</a></h1>
            <h2 class="site-description">朝闻道,夕死可矣.</h2>
        </div>
    </header><ol class="social-menu">
            
                <li>
                    <a 
                        href='https://github.com/CaiJimmy/hugo-theme-stack'
                        target="_blank"
                        title="GitHub"
                    >
                        
                        
                            <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-brand-github" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
  <path d="M9 19c-4.3 1.4 -4.3 -2.5 -6 -3m12 5v-3.5c0 -1 .1 -1.4 -.5 -2c2.8 -.3 5.5 -1.4 5.5 -6a4.6 4.6 0 0 0 -1.3 -3.2a4.2 4.2 0 0 0 -.1 -3.2s-1.1 -.3 -3.5 1.3a12.3 12.3 0 0 0 -6.2 0c-2.4 -1.6 -3.5 -1.3 -3.5 -1.3a4.2 4.2 0 0 0 -.1 3.2a4.6 4.6 0 0 0 -1.3 3.2c0 4.6 2.7 5.7 5.5 6c-.6 .6 -.6 1.2 -.5 2v3.5" />
</svg>



                        
                    </a>
                </li>
            
                <li>
                    <a 
                        href='https://twitter.com'
                        target="_blank"
                        title="Twitter"
                    >
                        
                        
                            <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-brand-twitter" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
  <path d="M22 4.01c-1 .49 -1.98 .689 -3 .99c-1.121 -1.265 -2.783 -1.335 -4.38 -.737s-2.643 2.06 -2.62 3.737v1c-3.245 .083 -6.135 -1.395 -8 -4c0 0 -4.182 7.433 4 11c-1.872 1.247 -3.739 2.088 -6 2c3.308 1.803 6.913 2.423 10.034 1.517c3.58 -1.04 6.522 -3.723 7.651 -7.742a13.84 13.84 0 0 0 .497 -3.753c-.002 -.249 1.51 -2.772 1.818 -4.013z" />
</svg>



                        
                    </a>
                </li>
            
        </ol><ol class="menu" id="main-menu">
        
        
        

        <li >
            <a href='/' >
                
                
                
                    <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-home" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z"/>
  <polyline points="5 12 3 12 12 3 21 12 19 12" />
  <path d="M5 12v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-7" />
  <path d="M9 21v-6a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v6" />
</svg>



                
                <span>Home</span>
            </a>
        </li>
        
        

        <li >
            <a href='/about/' >
                
                
                
                    <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-user" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z"/>
  <circle cx="12" cy="7" r="4" />
  <path d="M6 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2" />
</svg>



                
                <span>About</span>
            </a>
        </li>
        
        

        <li >
            <a href='/archives/' >
                
                
                
                    <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-archive" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z"/>
  <rect x="3" y="4" width="18" height="4" rx="2" />
  <path d="M5 8v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-10" />
  <line x1="10" y1="12" x2="14" y2="12" />
</svg>



                
                <span>Archives</span>
            </a>
        </li>
        
        

        <li >
            <a href='/search/' >
                
                
                
                    <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-search" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z"/>
  <circle cx="10" cy="10" r="7" />
  <line x1="21" y1="21" x2="15" y2="15" />
</svg>



                
                <span>Search</span>
            </a>
        </li>
        
        

        <li >
            <a href='/links/' >
                
                
                
                    <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-link" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z"/>
  <path d="M10 14a3.5 3.5 0 0 0 5 0l4 -4a3.5 3.5 0 0 0 -5 -5l-.5 .5" />
  <path d="M14 10a3.5 3.5 0 0 0 -5 0l-4 4a3.5 3.5 0 0 0 5 5l.5 -.5" />
</svg>



                
                <span>Links</span>
            </a>
        </li>
        

        <div class="menu-bottom-section">
                <li id="i18n-switch">  
                    <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-language" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
  <path d="M4 5h7" />
  <path d="M9 3v2c0 4.418 -2.239 8 -5 8" />
  <path d="M5 9c-.003 2.144 2.952 3.908 6.7 4" />
  <path d="M12 20l4 -9l4 9" />
  <path d="M19.1 18h-6.2" />
</svg>



                    <select name="language" onchange="window.location.href = this.selectedOptions[0].value">
                        
                            <option value="http://meruro.cn/" selected>English</option>
                        
                            <option value="http://meruro.cn/zh-cn/" >中文</option>
                        
                            <option value="http://meruro.cn/ar/" >عربي</option>
                        
                    </select>
                </li>
            
            
            
                <li id="dark-mode-toggle">
                    <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-toggle-left" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z"/>
  <circle cx="8" cy="12" r="2" />
  <rect x="2" y="6" width="20" height="12" rx="6" />
</svg>



                    <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-toggle-right" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z"/>
  <circle cx="16" cy="12" r="2" />
  <rect x="2" y="6" width="20" height="12" rx="6" />
</svg>



                    <span>Dark Mode</span>
                </li>
            
        </div>
    </ol>
</aside>
<main class="main full-width">
    <article class="main-article">
    <header class="article-header">

    <div class="article-details">
    

    <div class="article-title-wrapper">
        <h2 class="article-title">
            <a href="/p/redis%E5%92%8Ccelery%E7%AC%94%E8%AE%B0/">redis和celery笔记</a>
        </h2>
    
        
    </div>

    
    <footer class="article-time">
        
            <div>
                <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-calendar-time" width="56" height="56" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z"/>
  <path d="M11.795 21h-6.795a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v4" />
  <circle cx="18" cy="18" r="4" />
  <path d="M15 3v4" />
  <path d="M7 3v4" />
  <path d="M3 11h16" />
  <path d="M18 16.496v1.504l1 1" />
</svg>
                <time class="article-time--published">Jun 18, 2018</time>
            </div>
        

        
            <div>
                <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-clock" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z"/>
  <circle cx="12" cy="12" r="9" />
  <polyline points="12 7 12 12 15 15" />
</svg>



                <time class="article-time--reading">
                    4 minute read
                </time>
            </div>
        
    </footer>
    

    
</div>
</header>

    <section class="article-content">
    
    
    <h1 id="celery">celery</h1>
<h2 id="执行work">执行work</h2>
<p>/usr/local/python3.7/bin/python3.7 -m celery -A pucha worker -l info -n <a class="link" href="mailto:w1@localhost.localdomain" >w1@localhost.localdomain</a> &ndash;pidfile=/var/run/celery/w1.pid &ndash;logfile=/var/log/celery.log</p>
<h2 id="执行beat">执行beat</h2>
<p>celery -A pucha beat -l info -f /var/log/celery/celery.log &ndash;detach</p>
<h1 id="redis-cli使用">redis-cli使用</h1>
<p>string：字符串构建其他数据结构的基础</p>
<p>hash：哈希列表</p>
<p>list（可重复）：列表</p>
<p>set（不可重复无序）：集合，在哈希列表的基础上实现</p>
<p>sorted set（不可重复有序）：有序集合</p>
<p>使用场景</p>
<ol>
<li>去最新n个数据的操作</li>
<li>排行榜，取top n个数据 //最佳人气前10条</li>
<li>精确的设置过期时间</li>
<li>计数器</li>
<li>实时系统， 反垃圾系统</li>
<li>pub， sub发布订阅构建实时消息系统</li>
<li>构建消息队列</li>
<li>缓存</li>
</ol>
<p>cmd访问redis
redis-cli.exe -h 127.0.0.1 -p 6379</p>
<p>key
keys * 获取所有的key
select 0 选择第一个库
move myString 1 将当前的数据库key移动到某个数据库,目标库有，则不能移动
flush db      清除指定库
randomkey     随机key
type key      类型</p>
<pre><code>set key1 value1 设置key
get key1    获取key
mset key1 value1 key2 value2 key3 value3（mass大量，堆）
mget key1 key2 key3
del key1   删除key
exists key      判断是否存在key
expire key 10   10过期(单位是秒）
pexpire key 1000 毫秒（单位是毫秒）
persist key     删除过期时间
</code></pre>
<p>string
set name cxx
get name
getrange name 0 -1        字符串分段
getset name new_cxx       设置值，返回旧值
mset key1 key2            批量设置
mget key1 key2            批量获取
setnx key value           不存在就插入（not exists）
setex key time value      过期时间（expire）
setrange key index value  从index开始替换value
incr age        递增
incrby age 10   递增
decr age        递减
decrby age 10   递减
incrbyfloat     增减浮点数
append          追加
strlen          长度
getbit/setbit/bitcount/bitop    位操作</p>
<p>hash
hset myhash name cxx
hget myhash name
hmset myhash name cxx age 25 note &ldquo;i am notes&rdquo;
hmget myhash name age note<br>
hgetall myhash               获取所有的
hexists myhash name          是否存在
hsetnx myhash score 100      设置不存在的
hincrby myhash id 1          递增
hdel myhash name             删除
hkeys myhash                 只取key
hvals myhash                 只取value
hlen myhash                  长度</p>
<p>list
lpush mylist a b c  左插入
rpush mylist x y z  右插入
lrange mylist 0 -1  数据集合
lpop mylist  弹出元素
rpop mylist  弹出元素
llen mylist  长度
lrem mylist count value  删除
lindex mylist 2          指定索引的值
lset mylist 2 n          索引设值
ltrim mylist 0 4         删除key
linsert mylist before a  插入
linsert mylist after a   插入
rpoplpush list list2     转移列表的数据</p>
<p>set
sadd myset redis 
smembers myset       数据集合
srem myset set1         删除
sismember myset set1 判断元素是否在集合中
scard key_name       个数
sdiff | sinter | sunion 操作：集合间运算：差集 | 交集 | 并集
srandmember          随机获取集合中的元素
spop                 从集合中弹出一个元素</p>
<p>zset
zadd zset 1 one
zadd zset 2 two
zadd zset 3 three
zincrby zset 1 one              增长分数
zscore zset two                 获取分数
zrange zset 0 -1 withscores     范围值
zrangebyscore zset 10 25 withscores 指定范围的值
zrangebyscore zset 10 25 withscores limit 1 2 分页
Zrevrangebyscore zset 10 25 withscores  指定范围的值
zcard zset  元素数量
Zcount zset 获得指定分数范围内的元素个数
Zrem zset one two        删除一个或多个元素
Zremrangebyrank zset 0 1  按照排名范围删除元素
Zremrangebyscore zset 0 1 按照分数范围删除元素
Zrank zset 0 -1    分数最小的元素排名为0
Zrevrank zset 0 -1  分数最大的元素排名为0
Zinterstore
zunionstore rank:last_week 7 rank:20150323 rank:20150324 rank:20150325  weights 1 1 1 1 1 1 1</p>
<p>排序：
sort mylist  排序
sort mylist alpha desc limit 0 2 字母排序
sort list by it:* desc           by命令
sort list by it:* desc get it:*  get参数
sort list by it:* desc get it:* store sorc:result  sort命令之store参数：表示把sort查询的结果集保存起来</p>
<p>订阅与发布：
订阅频道：subscribe chat1
发布消息：publish chat1 &ldquo;hell0 ni hao&rdquo;
查看频道：pubsub channels
查看某个频道的订阅者数量: pubsub numsub chat1
退订指定频道： unsubscrible chat1   , punsubscribe java.*
订阅一组频道： psubscribe java.*</p>
<p>redis事物：
隔离性，原子性， 
步骤：  开始事务，执行命令，提交事务
multi  //开启事务
sadd myset a b c
sadd myset e f g
lpush mylist aa bb cc
lpush mylist dd ff gg</p>
<p>服务器管理
dump.rdb
appendonly.aof
//BgRewriteAof 异步执行一个aop(appendOnly file)文件重写
会创建当前一个AOF文件体积的优化版本</p>
<pre><code>//BgSave 后台异步保存数据到磁盘，会在当前目录下创建文件dump.rdb
//save同步保存数据到磁盘，会阻塞主进程，别的客户端无法连接

//client kill 关闭客户端连接
//client list 列出所有的客户端

//给客户端设置一个名称
  client setname myclient1
  client getname
  
 config get port
 //configRewrite 对redis的配置文件进行改写
</code></pre>
<p>rdb 
save 900 1
save 300 10
save 60 10000</p>
<p>aop备份处理
appendonly yes    开启持久化
appendfsync everysec  每秒备份一次</p>
<p>命令：
bgsave异步保存数据到磁盘（快照保存）
lastsave返回上次成功保存到磁盘的unix的时间戳
shutdown同步保存到服务器并关闭redis服务器
bgrewriteaof文件压缩处理（命令）</p>
<h1 id="celery理解">celery理解</h1>
<p>是一个基于python开发的模块,可以帮我们对任务进行分发和处理,celery5.x以下支持python2.7,以上只支持python3.5+
用户请求一个网站/应用中的耗时任务时,将此耗时任务放入broker队列,队列此时返回一个任务id给用户,而耗时应用会在后台通过worker异步执行,如果执行完成放入backend队列
用户使用此id再次请求此任务处理结果时,返回完成backend队列中的结果
(broker队列中的任务可以立即执行,也可以延时/定时执行,给队列中的耗时任务传两个参数,第一个调用函数名,第二个函数参数,可以省略worker的编写
例如 result=x1.delay(4,4) 会执行x1函数,并将(4,4)传入x1中 result是一个对象,result.id即为任务id</p>
<h1 id="环境搭建">环境搭建</h1>
<p>pip install celery==4.4.0
安装broker: redis或rabbitMQ
pip3 install redis / pika
!django中使用django-celery自动帮我们设置好目录
pip install django-celery
需要按照django-celery</p>
<h1 id="在django中使用">在django中使用</h1>
<h1 id="第一步在settings中设置">第一步,在settings中设置</h1>
<p>########################### django-celery 配置 ##########################
CELERY_BORKER_URL = &lsquo;redis://62.234.18.148:6379&rsquo;
CELERY_ACCEPT_CONTENT= [&lsquo;json&rsquo;]
CELERY_RESULT_BACKEND = &lsquo;redis://62.234.18.148:6379&rsquo;
CELERY_TASK_SERIALIZER = &lsquo;json&rsquo;</p>
<h1 id="第二步在项目名下新建celerypy文件">第二步,在项目名下新建celery.py文件</h1>
<p>#!/usr/bin/env python</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="c1"># -*- coding:utf-8 -*-</span>
</span></span><span class="line"><span class="cl"><span class="kn">import</span> <span class="nn">os</span>
</span></span><span class="line"><span class="cl"><span class="kn">from</span> <span class="nn">celery</span> <span class="kn">import</span> <span class="n">Celery</span>
</span></span><span class="line"><span class="cl"><span class="c1"># set the default Django settings module for the &#39;celery&#39; program.</span>
</span></span><span class="line"><span class="cl"><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="o">.</span><span class="n">setdefault</span><span class="p">(</span><span class="s1">&#39;DJANGO_SETTINGS_MODULE&#39;</span><span class="p">,</span> <span class="s1">&#39;auction.settings&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">app</span> <span class="o">=</span> <span class="n">Celery</span><span class="p">(</span><span class="s1">&#39;auction&#39;</span><span class="p">)</span><span class="c1">#实例化celery对象,不需要加参数borker=</span>
</span></span><span class="line"><span class="cl"><span class="c1"># Using a string here means the worker doesn&#39;t have to serialize</span>
</span></span><span class="line"><span class="cl"><span class="c1"># the configuration object to child processes.</span>
</span></span><span class="line"><span class="cl"><span class="c1"># - namespace=&#39;CELERY&#39; means all celery-related configuration keys</span>
</span></span><span class="line"><span class="cl"><span class="c1">#   should have a `CELERY_` prefix.</span>
</span></span><span class="line"><span class="cl"><span class="n">app</span><span class="o">.</span><span class="n">config_from_object</span><span class="p">(</span><span class="s1">&#39;django.conf:settings&#39;</span><span class="p">,</span> <span class="n">namespace</span><span class="o">=</span><span class="s1">&#39;CELERY&#39;</span><span class="p">)</span><span class="c1">#定义配置文件的路径</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># Load task modules from all registered Django app configs.</span>
</span></span><span class="line"><span class="cl"><span class="c1">#以后会去每个已注册的app中读取tasks.py文件</span>
</span></span><span class="line"><span class="cl"><span class="n">app</span><span class="o">.</span><span class="n">autodiscover_tasks</span><span class="p">()</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h1 id="第三步项目appsapp名称-新建taskspy文件">第三步,项目/apps/app名称/ ,新建tasks.py文件</h1>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="kn">from</span> <span class="nn">celery</span> <span class="kn">import</span> <span class="n">shared_task</span>
</span></span><span class="line"><span class="cl"><span class="nd">@share_task</span>
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="n">x</span><span class="o">+</span><span class="n">y</span>
</span></span><span class="line"><span class="cl"><span class="nd">@shared_task</span>
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">nul</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="n">x</span><span class="o">*</span><span class="n">y</span>
</span></span><span class="line"><span class="cl">	
</span></span><span class="line"><span class="cl"><span class="n">定时任务result</span><span class="o">=</span><span class="n">tasks</span><span class="o">.</span><span class="n">x1</span><span class="o">.</span><span class="n">apply_async</span><span class="p">(</span><span class="n">args</span><span class="o">=</span><span class="p">[</span><span class="n">参数</span><span class="p">,],</span><span class="n">eta</span><span class="o">=</span><span class="s1">&#39;执行的时间,格式必须为UTC格式&#39;</span><span class="p">);</span><span class="k">return</span> <span class="n">result</span><span class="o">.</span><span class="n">id</span>
</span></span><span class="line"><span class="cl"><span class="n">普通任务result</span><span class="o">=</span><span class="n">tasks</span><span class="o">.</span><span class="n">x1</span><span class="o">.</span><span class="n">delay</span><span class="p">(</span><span class="mi">4</span><span class="p">,</span><span class="mi">4</span><span class="p">)</span> <span class="n">会执行x1函数</span><span class="p">,</span><span class="n">并将</span><span class="p">(</span><span class="mi">4</span><span class="p">,</span><span class="mi">4</span><span class="p">)</span><span class="n">传入x1中</span> <span class="n">result是一个对象</span><span class="p">,</span><span class="n">result</span><span class="o">.</span><span class="n">id即为任务id</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h1 id="第四步项目名称下__init__">第四步,项目名称下__init__</h1>
<p>from .celery import app
<strong>all</strong> = (&ldquo;app&rdquo;)</p>
<h1 id="启动worker">启动worker</h1>
<p>启动redis
进入celery文件目录
celery -A s1 -l info
-A匹配文件名,如s1  -l日志功能 写入info
创建任务
python s2.py , s3.py #运行装饰器装饰的函数即为创建任务
最后启动django项目</p>

</section>


    <footer class="article-footer">
    
    <section class="article-tags">
        
            <a href="/tags/%E4%BB%A3%E7%A0%81/">代码</a>
        
    </section>


    
    <section class="article-copyright">
        <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-copyright" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z"/>
  <circle cx="12" cy="12" r="9" />
  <path d="M14.5 9a3.5 4 0 1 0 0 6" />
</svg>



        <span>Licensed under CC BY-NC-SA 4.0</span>
    </section>
    </footer>


    
</article>

    

    

     
    
        
    

    <footer class="site-footer">
    <section class="copyright">
        &copy; 
        
            2020 - 
        
        2023 梅鲁梅鲁梅鲁梅~
    </section>
    
    <section class="powerby">
        Built with <a href="https://gohugo.io/" target="_blank" rel="noopener">Hugo</a> <br />
        Theme <b><a href="https://github.com/CaiJimmy/hugo-theme-stack" target="_blank" rel="noopener" data-version="3.13.0">Stack</a></b> designed by <a href="https://jimmycai.com" target="_blank" rel="noopener">Jimmy</a>
    </section>
</footer>


    
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    
    <div class="pswp__bg"></div>

    
    <div class="pswp__scroll-wrap">

        
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                
                
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div><script 
                src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"integrity="sha256-ePwmChbbvXbsO02lbM3HoHbSHTHFAeChekF1xKJdleo="crossorigin="anonymous"
                defer
                >
            </script><script 
                src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"integrity="sha256-UKkzOn/w1mBxRmLLGrSeyB4e1xbrp4xylgAWb3M42pU="crossorigin="anonymous"
                defer
                >
            </script><link 
                rel="stylesheet" 
                href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css"crossorigin="anonymous"
            ><link 
                rel="stylesheet" 
                href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css"crossorigin="anonymous"
            >

            </main>
    <aside class="sidebar right-sidebar sticky">
        
            
                
    <section class="widget archives">
        <div class="widget-icon">
            <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-hash" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z"/>
  <line x1="5" y1="9" x2="19" y2="9" />
  <line x1="5" y1="15" x2="19" y2="15" />
  <line x1="11" y1="4" x2="7" y2="20" />
  <line x1="17" y1="4" x2="13" y2="20" />
</svg>



        </div>
        <h2 class="widget-title section-title">Table of contents</h2>
        
        <div class="widget--toc">
            <nav id="TableOfContents">
  <ol>
    <li><a href="#执行work">执行work</a></li>
    <li><a href="#执行beat">执行beat</a></li>
  </ol>
</nav>
        </div>
    </section>

            
        
    </aside>


        </div>
        <script 
                src="https://cdn.jsdelivr.net/npm/node-vibrant@3.1.6/dist/vibrant.min.js"integrity="sha256-awcR2jno4kI5X0zL8ex0vi2z&#43;KMkF24hUW8WePSA9HM="crossorigin="anonymous"
                
                >
            </script><script type="text/javascript" src="/ts/main.js" defer></script>
<script>
    (function () {
        const customFont = document.createElement('link');
        customFont.href = "https://fonts.googleapis.com/css2?family=Lato:wght@300;400;700&display=swap";

        customFont.type = "text/css";
        customFont.rel = "stylesheet";

        document.head.appendChild(customFont);
    }());
</script>

    </body>
</html>
